import React, { useRef, useState } from 'react';
import _ from 'lodash';
import { Button, Dropdown, Menu, message, Popconfirm, Tooltip, Modal, TreeSelect } from 'antd';
import CommonTable from '@/components/CommonTable';
import UserDialog from './components/userDialog';
import DistributionDialog from './components/distributionDialog';
import DebounceWrapper from '@/components/DebounceWrapper';
import {
  DeleteOutlined,
  EditOutlined,
  InfoCircleOutlined,
  PlusOutlined,
  ApartmentOutlined,
  UnlockOutlined,
  MoreOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import {
  fetchUserData,
  deleteUserById,
  batchDeleteUserByIds,
  resetPassword,
} from '@/services/system/user';
import { fetchDepartmentList } from '@/services/system/department';
import { formatTree } from '@/utils/utils';

const DebounceButton = DebounceWrapper(Button);

export default () => {
  const tableRef = useRef(null);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
  const [userFormVisible, setUserFormVisible] = useState(false);
  const [userFormOptions, setUserFormOptions] = useState({});
  const [distributionDialogVisible, setDistributionDialogVisible] = useState(false);
  const [distributionDialogOptions, setDistributionDialogOptions] = useState({});

  // 切换loading
  const toggleDeleteLoading = (id, status) => {
    setDeleteLoadingIds((list) => {
      const nextList = [...list];
      if (status) {
        nextList.push(id);
      } else {
        const index = _.indexOf(nextList, id);
        if (index > -1) {
          nextList.splice(index, 1);
        }
      }
      return nextList;
    });
  };

  return (
    <>
      <CommonTable
        ref={tableRef}
        indexRender
        rowKey={'userId'}
        rowSelection={{ getCheckboxProps: (data) => ({ disabled: data.userType !== '2' }) }}
        header={{
          headerTitle: '用户列表',
          headerToolsRender: true,
          headerButtonList: [
            {
              key: 'add',
              type: 'primary',
              label: '新增',
              icon: <PlusOutlined />,
            },
            {
              key: 'delete',
              danger: true,
              type: 'primary',
              label: '批量删除',
              loading: deleteLoading,
              confirmText: '确认批量删除所勾选的用户账号？',
              icon: <DeleteOutlined />,
            },
          ],
          headerButtonClick: async ({ key }) => {
            switch (key) {
              case 'add':
                setUserFormVisible(true);
                break;
              case 'delete':
                const { refresh, getSelectedList } = tableRef.current;
                if (getSelectedList) {
                  const selectedList = getSelectedList();
                  if (selectedList && selectedList.length) {
                    setDeleteLoading(true);
                    try {
                      await batchDeleteUserByIds({ ids: _.map(selectedList, 'userId') });
                      refresh && refresh();
                      message.success('用户数据批量删除成功');
                    } catch (e) {
                      console.log('删除失败');
                    }
                    setDeleteLoading(false);
                  } else {
                    message.warning('请至少选择一项数据后再操作');
                  }
                }
                break;
            }
          },
        }}
        request={async (params) => {
          const { records, total } = await fetchUserData(params);
          console.log(records);
          return { data: records, count: total };
        }}
        search={[
          {
            key: 'organList',
            Component: TreeSelect,
            searchType: 'IN',
            props: {
              label: '机构',
              initialValue: [],
            },
            componentProps: {
              multiple: true,
              allowClear: true,
              maxTagCount: 'responsive',
              placeholder: '请选择所属机构',
              asyncOptions: {
                asyncRequest: async () => {
                  const res = await fetchDepartmentList({ size: -1, current: 1 });
                  return {
                    treeData: formatTree(res, ({ organName, id }) => ({
                      key: id,
                      value: id,
                      title: organName,
                    })),
                  };
                },
              },
            },
          },
        ]}
        columns={[
          { title: '用户账号', dataIndex: 'userName', columnControl: { typeList: 'search' } },
          { title: '用户昵称', dataIndex: 'nickName', columnControl: { typeList: 'search' } },
          {
            title: '用户类型',
            dataIndex: 'userType',
            columnControl: { typeList: 'filter', filterDictType: 'user_type' },
          },
          {
            title: '用户状态',
            dataIndex: 'userStatus',
            columnControl: { typeList: 'filter', filterDictType: 'user_status' },
          },
          {
            title: '所属机构',
            dataIndex: 'organList',
            render: (list) => (_.isArray(list) ? _.map(list, 'organName').join('、') : ''),
          },
          { title: '真实姓名', dataIndex: 'realName', columnControl: { typeList: 'search' } },
          {
            title: '性别',
            dataIndex: 'sex',
            columnControl: { typeList: 'filter', filterDictType: 'sex' },
          },
          { title: '员工号', dataIndex: 'staffId', columnControl: { typeList: 'search' } },
          { title: '身份证号', dataIndex: 'identity', columnControl: { typeList: 'search' } },
          { title: '联系电话', dataIndex: 'phone', columnControl: { typeList: 'search' } },
          { title: '邮箱', dataIndex: 'email' },
          {
            title: (
              <>
                操作
                <Tooltip placement="top" title={'系统预设用户暂不支持编辑、删除等操作'}>
                  <InfoCircleOutlined className="tooltip-information-handle-icon" />
                </Tooltip>
              </>
            ),
            fixed: 'right',
            dataIndex: 'userId',
            width: 220,
            render: (text, data) => {
              const isDefaultUser = data.userType !== '2';
              const deleteLoading = _.includes(deleteLoadingIds, text);

              return (
                <>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    disabled={deleteLoading || isDefaultUser}
                    onClick={() => {
                      setUserFormOptions(data);
                      setUserFormVisible(true);
                    }}
                  >
                    编辑
                  </DebounceButton>
                  <Popconfirm
                    okText="确定"
                    cancelText="取消"
                    title={'确认删除该用户，删除后不可恢复'}
                    placement="topRight"
                    onConfirm={async () => {
                      toggleDeleteLoading(text, true);
                      try {
                        await deleteUserById({ id: text });
                        const { refresh } = tableRef.current;
                        refresh && refresh();
                        message.success('用户删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      toggleDeleteLoading(text, false);
                    }}
                  >
                    <DebounceButton
                      danger
                      type="link"
                      size="small"
                      icon={<DeleteOutlined />}
                      loading={deleteLoading}
                      disabled={isDefaultUser}
                    >
                      删除
                    </DebounceButton>
                  </Popconfirm>
                  <Dropdown
                    trigger={['click']}
                    disabled={deleteLoading}
                    overlay={
                      <Menu
                        items={[
                          {
                            key: 'roleDistribute',
                            icon: <ApartmentOutlined />,
                            label: '分配岗位、角色',
                          },
                          {
                            key: 'resetPassword',
                            icon: <UnlockOutlined />,
                            label: '重置密码',
                          },
                        ]}
                        onClick={({ key }) => {
                          const nameText = data.nickName || data.realName || '';
                          switch (key) {
                            case 'roleDistribute':
                              setDistributionDialogOptions(data);
                              setDistributionDialogVisible(true);
                              break;
                            case 'resetPassword':
                              Modal.confirm({
                                title: '密码重置',
                                icon: <ExclamationCircleOutlined />,
                                content: `确认重置用户${
                                  nameText ? '：' + nameText + ' 的' : ''
                                }密码为初始密码？`,
                                okText: '确定',
                                cancelText: '取消',
                                onOk() {
                                  resetPassword({ id: text }).then(() => {
                                    message.success(
                                      `用户${nameText ? '：' + nameText + ' 的' : ''}密码重置成功`,
                                    );
                                  });
                                },
                              });
                              break;
                          }
                        }}
                      />
                    }
                  >
                    <DebounceButton type="text" size="small">
                      更多
                      <MoreOutlined />
                    </DebounceButton>
                  </Dropdown>
                </>
              );
            },
          },
        ]}
      />
      <UserDialog
        visible={userFormVisible}
        options={userFormOptions}
        closeModal={() => {
          setUserFormOptions({});
          setUserFormVisible(false);
        }}
        updateList={() => {
          const { refresh } = tableRef.current;
          refresh && refresh();
        }}
      />
      <DistributionDialog
        visible={distributionDialogVisible}
        options={distributionDialogOptions}
        closeModal={() => {
          setDistributionDialogOptions({});
          setDistributionDialogVisible(false);
        }}
      />
    </>
  );
};
